//
//  FoodDetailNewTVC.m
//  FaceCard
//
//  Created by 瞿伦平 on 2016/10/17.
//  Copyright © 2016年 瞿伦平. All rights reserved.
//

#import "FoodDetailNewTVC.h"
#import "MJRefresh.h"
#import "UIImageView+AFNetworking.h"

#import <CoreText/CoreText.h>
#import "NSString+WPAttributedMarkup.h"
#import "WPAttributedStyleAction.h"
#import "WPHotspotLabel.h"

#import "UIButton+JKBadge.h"
#import "FoodGoodsTableViewCell.h"

#import "UIButton+JKBlock.h"
#import "UIButton+JKBackgroundColor.h"
#import "UIView+JKBlockGesture.h"
#import "UIButton+JKImagePosition.h"
#import "UINavigationBar+JKAwesome.h"
#import "UINavigationBar+Awesome.h"
#import "UIBarButtonItem+BlocksKit.h"

#import "PurchaseCarAnimationTool.h"

#import "AppDelegate.h"


#import "ShopCommentTableViewCell.h"

#import "NSDate+DateTools.h"


#import "GXDPPayViewController.h"

#import "PinJiaCell.h"
#import "PingJiaViewController.h"


#pragma mark----底部view
@implementation FoodBottomView
-(id)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        UIView *superView = self;
        int padding = 10;
        
        
        self.cartLogoBtn = [superView newUIButton];
        [self.cartLogoBtn jk_setBackgroundColor:COLOR(242, 242, 242) forState:UIControlStateNormal];
        self.cartLogoBtn.userInteractionEnabled = NO;
        [self.cartLogoBtn setImage:IMG(@"购物车.png") forState:UIControlStateNormal];
        self.cartLogoBtn.jk_shouldHideBadgeAtZero = YES;
        
        
        self.moneyLable = [superView newUILableWithText:@"" textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:13]];
        self.moneyLable.numberOfLines = 0;
        
        self.buyBtn = [superView newUIButton];
        [self.buyBtn setTitle:@"去结算" forState:UIControlStateNormal];
        [self.buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.buyBtn jk_setBackgroundColor:COLOR(27, 196, 157) forState:UIControlStateNormal];
        
        [self.cartLogoBtn makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(superView);
            make.width.equalTo(_cartLogoBtn.height);
        }];
        [self.moneyLable makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_cartLogoBtn.right).offset(padding);
            make.top.bottom.equalTo(superView);
            make.right.equalTo(_buyBtn.left).offset(-padding/2);
        }];
        
        [self.buyBtn makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.right.equalTo(superView);
            make.width.equalTo(80);
        }];
        
        NSLog(@"price:%@",self.moneyLable.text);
        self.moneyShowWhenShopCarShowLable = [superView newUILableWithText:@"" textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:13]];
        self.moneyShowWhenShopCarShowLable.numberOfLines = 0;
        [self.moneyShowWhenShopCarShowLable makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(superView.left).offset(padding);
            make.top.bottom.equalTo(superView);
            make.right.equalTo(_buyBtn.left).offset(-padding/2);
        }];
        
        [self isShowShopCarView:NO];
    }
    return self;
}

-(void)reloadWithTotalMoney:(float)money shippingFee:(float)shippingFee goodsCount:(int)count
{
    NSDictionary* style = @{@"body1" : @[[UIFont systemFontOfSize:14], [UIColor darkGrayColor]],
                            @"body2" : @[[UIFont boldSystemFontOfSize:15], [UIColor grayColor]],
                            @"body3" : @[[UIFont systemFontOfSize:12], [UIColor grayColor]] };
    
    
    NSMutableString *str = [NSMutableString new];
    [str appendFormat:@"<body1>小计：</body1><body2>¥%.2f</body2>", money];
    
    if (money <= 0) {
        self.buyBtn.enabled = NO;
    } else {
        self.buyBtn.enabled = YES;
        [str appendFormat:@"\n<body3>另需¥%.2f配送费</body3>", shippingFee];
    }
    
    self.moneyLable.attributedText = [str attributedStringWithStyleBook:style];
    self.moneyShowWhenShopCarShowLable.attributedText = [str attributedStringWithStyleBook:style];
    
    if (count > 0) {
        self.cartLogoBtn.jk_badgeValue = StringWithInt(count);
        self.cartLogoBtn.jk_badgeOriginX = kZEFooterHight-10;
    } else
        self.cartLogoBtn.jk_badgeValue = @"";
}

-(void)isShowShopCarView:(BOOL)isShow
{
    if (isShow == NO) {
        self.moneyShowWhenShopCarShowLable.hidden = YES;
        self.cartLogoBtn.hidden = NO;
        self.moneyLable.hidden = NO;
    } else {
        self.moneyShowWhenShopCarShowLable.hidden = NO;
        self.cartLogoBtn.hidden = YES;
        self.moneyLable.hidden = YES;
    }
}

@end


#pragma mark----顶部商铺信息view
@implementation FoodHeaderView
-(id)init
{
    self = [super init];
    if (self) {
        self.backgroundColor = COLOR(242, 242, 242);
        UIView *superView = self;
        int padding = 10;
        
        
        self.shopImgLunView = [[ImagePlayerView alloc] init];
        self.shopImgLunView.backgroundColor = [UIColor greenColor];
        //self.shopImgLunView.imagePlayerViewDelegate = self;
        //self.lunView.scrollInterval = 0.0f;
        self.shopImgLunView.pageControlPosition = ICPageControlPosition_BottomCenter;
        //self.lunView.hidePageControl = NO;
        self.shopImgLunView.endlessScroll = YES;
        self.shopImgLunView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_shopImgLunView];
        
        [self.shopImgLunView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(superView);
            //make.height.equalTo(_lunView.width).multipliedBy(0.427);
            //make.height.equalTo(280);
        }];
        
        
        UIView *aView = ({
            UIView *view = [superView newUIViewWithBgColor:[UIColor whiteColor]];
            
            self.shopNameLable = [view newUILableWithText:@"" textColor:[UIColor blackColor] font:[UIFont systemFontOfSize:13]];
            self.shopNameLable.numberOfLines = 0;
            
            self.shopDesLable = [view newUILableWithText:@"" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:11]];
            self.shopDesLable.numberOfLines = 0;
            
            self.shopAddressLable = [view newUILableWithText:@"" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:11]];
            self.shopAddressLable.numberOfLines = 0;
            
            [self.shopNameLable makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(view.left).offset(padding);
                make.right.equalTo(view.right).offset(-padding);
                make.top.equalTo(_shopImgLunView.bottom).offset(padding/2);
                make.height.equalTo(20);
            }];
            [self.shopDesLable makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.height.equalTo(_shopNameLable);
                make.top.equalTo(_shopNameLable.bottom);
            }];
            [self.shopAddressLable makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.height.equalTo(_shopNameLable);
                make.top.equalTo(_shopDesLable.bottom);
            }];
            
            HCSStarRatingView *starRatingView = [[HCSStarRatingView alloc] init];
            starRatingView.maximumValue = 5;
            starRatingView.minimumValue = 0;
            starRatingView.value = 0;
            starRatingView.spacing = 1;
            starRatingView.tag = 21;
            starRatingView.tintColor = STAR_COLOR;
            starRatingView.backgroundColor = [UIColor clearColor];
            starRatingView.allowsHalfStars = YES;
            starRatingView.userInteractionEnabled = NO;
            [view addSubview:starRatingView];
            self.starView = starRatingView;
            
            [starRatingView makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_shopNameLable.left);
                make.top.equalTo(_shopAddressLable.bottom);
                make.height.equalTo(20);
                make.width.equalTo(70);
            }];
            
            self.shopOrderLable = [view newUILableWithText:@"订单总数：0" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:11]];
            [self.shopOrderLable makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(starRatingView);
                make.left.equalTo(starRatingView.right).offset(padding);
                make.right.equalTo(_shopNameLable.right);
            }];
            [view makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(starRatingView.bottom).offset(padding/2);
            }];
            view;
        });
        [aView updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(superView);
            make.top.equalTo(_shopImgLunView.bottom);
            make.bottom.equalTo(superView.bottom).offset(-padding);
        }];

    }
    return self;
}
@end





#pragma mark----购物车顶部view
@implementation FoodShopCarHeaderView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = COLOR(242, 242, 242);
        UIView *superView = self;
        int padding = 10;
        
        UIView *sView = [superView newUIViewWithBgColor:COLOR(68, 135, 251)];
        [sView makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(superView.left).offset(padding);
            make.centerY.equalTo(superView.centerY);
            make.width.equalTo(3);
            make.height.equalTo(15);
        }];
        
        UILabel *lable = [superView newUILableWithText:@"已选商品" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:13]];
        [lable makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(sView.right).offset(padding/2);
            make.top.bottom.equalTo(superView);
        }];
        
        CGFloat clearnBtnWidth = 70;
        UIButton *clearBtn = [superView newUIButton];
        //clearBtn.frame = CGRectMake(frame.size.width - clearnBtnWidth, 0, clearnBtnWidth, frame.size.height);
        clearBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [clearBtn setTitle:@"清空" forState:UIControlStateNormal];
        [clearBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [clearBtn setImage:IMG(@"删除.png") forState:UIControlStateNormal];
        [clearBtn jk_setImagePosition:LXMImagePositionLeft spacing:3];
        self.clearBtn = clearBtn;
        [clearBtn makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.equalTo(superView);
            make.width.equalTo(clearnBtnWidth);
        }];
        
    }
    return self;
}
@end

#pragma mark----购物车view
@implementation FoodShopCarView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:0.75];
        UIView *superView = self;
        
        self.mShopCarListView = [UITableView new];
        //self.mShopCarListView.frame = CGRectMake(0, frame.size.height, DEVICE_Width, DEVICE_Height/2);
        //self.mShopCarListView.delegate = self;
        //self.mShopCarListView.dataSource = self;
        self.mShopCarListView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.mShopCarListView.backgroundColor = [UIColor clearColor];
        self.mShopCarListView.showsVerticalScrollIndicator = NO;
        self.mShopCarListView.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.mShopCarListView];
        
        
        FoodShopCarHeaderView *view = [[FoodShopCarHeaderView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_Width, kShopCarListView_HeaderViewHeight)];
        self.mShopCarListHeaderView = view;
        self.mShopCarListView.tableHeaderView = view;
        self.mShopCarListView.backgroundColor = [UIColor whiteColor];
        self.mShopCarListView.tableFooterView = [UIView new];
        
        [self.mShopCarListView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(superView);
            make.bottom.equalTo(superView.bottom).offset(-kZEFooterHight);
            make.height.equalTo(1);
        }];
        
    }
    return self;
}


@end



#pragma mark----购物车view１１１
@implementation FoodShopCarAndBottemView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        UIView *superView = self;
        
        self.selectArr = [NSMutableArray array];
        
        
        self.mShopCarView = [[FoodShopCarView alloc] initWithFrame:CGRectZero];
        self.mShopCarView.mShopCarListView.delegate = self;
        self.mShopCarView.mShopCarListView.dataSource = self;
        //self.mShopCarView.alpha = 0;
        [superView addSubview:self.mShopCarView];
        
        
        [self.mShopCarView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(superView);
            make.height.equalTo(DEVICE_Height);
        }];
        
        
        self.bottomView = [[FoodBottomView alloc] init];
        [superView addSubview:_bottomView];
        [self.bottomView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(superView);
            make.height.equalTo(kZEFooterHight);
        }];
        
        [self initShopCarView];
    }
    return self;
}


//判断购物车数据，对应id的数量
-(int)countFromCartDicWithId:(NSString *)iD
{
    int count = 0;
    for (FoodGoods *it in _selectArr) {
        if ([it.iD isEqualToString:iD]) {
            count = it.num;
            break;
        }
    }
    return count;
}

-(void)setCartArrWithItem:(FoodGoods *)item
{
    BOOL isNew = YES;
    
    for (int i=0; i<_selectArr.count; i++) {
        FoodGoods *it = [_selectArr objectAtIndex:i];
        if ([it.iD isEqualToString:item.iD]) {
            isNew = NO;
            if (item.num > 0) {
                it.num = item.num;
                [self.selectArr replaceObjectAtIndex:i withObject:it];
            } else {
                [self.selectArr removeObjectAtIndex:i];
            }
            break;
        }
    }
    
    if (isNew == YES) {
        [self.selectArr addObject:item];
    }
    
    [self.mShopCarView.mShopCarListView reloadData];
    
    [self updateBottomViewUIWithData];
}

-(void)reSetCartArr:(NSArray *)arr
{
    [self.selectArr setArray:arr];
    
    [self.mShopCarView.mShopCarListView reloadData];
    
    [self updateBottomViewUIWithData];
}

-(void)setShippingFeeWithMoney:(float)money
{
    self.total_money_fee = money;
    [self updateBottomViewUIWithData];
}

//获取需要传值的商品信息
-(NSMutableArray *)getGoodsInfoArrWithShopId:(NSString *)shopId
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<_selectArr.count; i++) {
        FoodGoods *item = [_selectArr objectAtIndex:i];

        NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
        [itemDic setNeedStr:item.name forKey:@"productname"];
        [itemDic setNeedStr:item.iD forKey:@"productid"];
        [itemDic setObject:[NSString stringWithFormat:@"%.2f", item.price] forKey:@"unitprice"];
        [itemDic setInt:item.num forKey:@"quantity"];
        [itemDic setObject:@"1" forKey:@"orderid"];
        [arr addObject:itemDic];
    }
    
    return arr;
}


- (void)updateBottomViewUIWithData
{
    int count = 0; //菜品数量
    float money = 0; //总金额
    if (_selectArr.count > 0) {
        for (FoodGoods *it in _selectArr) {
            count += it.num;
            money += (it.price * it.num);
        }
    }
    
    self.total_money = money;
    NSString *SumPrice = [NSString stringWithFormat:@"%.2f",self.total_money];
    [user setObject:SumPrice forKey:@"SumPrice"];
    [user setObject:@(_total_money_fee) forKey:@"sendPrice"];
    
    
    [self.bottomView reloadWithTotalMoney:money shippingFee:_total_money_fee goodsCount:count];
    
    [self updateShopCarUICons];
}

- (void)initShopCarView
{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.mShopCarView addGestureRecognizer:tap];
    
    
    [self.mShopCarView.mShopCarListHeaderView.clearBtn jk_addActionHandler:^(NSInteger tag) {
        [self.selectArr removeAllObjects];
        [self.mShopCarView.mShopCarListView reloadData];
        //[self.mainView.tableView reloadData];
        [self updateBottomViewUIWithData];
        
        if (self.successClearnCallBack)
            self.successClearnCallBack();
        MLLog(@"清空购物车");
    }];
    
    //显示购物车
    [self.bottomView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [self showShopList];
    }];
}

- (void)tapAction:(UITapGestureRecognizer *)sender{
    [self hiddenShopList];
}

- (void)showShopList
{
    [self bringSubviewToFront:self.mShopCarView];
    [self bringSubviewToFront:self.bottomView];
    [self.mShopCarView.mShopCarListView reloadData];
    
    [self.bottomView isShowShopCarView:YES];
    
    //self.mShopCarView.hidden = NO;
    
    [self updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(DEVICE_Height);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.mShopCarView.alpha = 1;
    }];
    

    
    [self updateShopCarUICons];
}

-(void)updateShopCarUICons
{
    NSUInteger count = 0;
    if (_selectArr.count > 0) {
        count = _selectArr.count;
    }
    
    CGFloat height = kShopCarListView_HeaderViewHeight + count * kShopCarListView_CellViewHeight;
    
    if (height > kShopCarListView_MaxHeight)
        height = kShopCarListView_MaxHeight;
    
    if (self.mShopCarView.frame.size.height != height) {
        [self.mShopCarView.mShopCarListView updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(height);
        }];
    }
}

- (void)hiddenShopList
{
    [self.bottomView isShowShopCarView:NO];
    
    //self.mShopCarView.hidden = YES;
    
    [self updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(kZEFooterHight);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.mShopCarView.alpha = 0;
        [self.mShopCarView.mShopCarListView updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(1);
        }];
    }];
}


#pragma mark----tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return _selectArr.count;
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kShopCarListView_CellViewHeight;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *CellIdentifier = @"ClassGoodsTableViewCell33";
        FoodGoodsTableViewCell *cell = (FoodGoodsTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell= [[FoodGoodsTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier isCartCell:YES];
        }
        if (indexPath.section == 0) {
            FoodGoods* item = [_selectArr objectAtIndex:indexPath.row];
            
            int count = [self countFromCartDicWithId:item.iD];
            
            cell.jianBtn.hidden = NO;
            cell.addBtn.hidden = NO;
            cell.countLable.hidden = NO;
            
            cell.nameLable.text = item.name.length>0 ? item.name : @"暂无";
            cell.priceLable.text = [NSString strRMBWithMoney:item.price * count];
            cell.count = count;
            
            cell.jianCallBack = ^(int count, FoodGoodsTableViewCell *tagCell) {
                item.num = count;
                [self setCartArrWithItem:item];
                
                if (self.successEditNumCallBack)
                    self.successEditNumCallBack(item);
            };
            
            cell.addCallBack = ^(int count, FoodGoodsTableViewCell *tagCell) {
                item.num = count;
               [self setCartArrWithItem:item];
                
                if (self.successEditNumCallBack)
                    self.successEditNumCallBack(item);
            };
            
        }
        
        
        return cell;
}

@end



#pragma mark----FoodContentView
@implementation FoodContentView
-(id)init
{
    self = [super init];
    if (self) {
        //self.backgroundColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:0.75];
        UIView *superView = self;
        
        self.titlesButtonArray = [NSMutableArray array];
        
        self.headerView = [[FoodHeaderView alloc] init];
        //self.headerView.frame = CGRectMake(0, 0, DEVICE_Width, kZEHeaderBaseInfoHight);
        [superView addSubview:_headerView];
        [self.headerView updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(superView);
            make.height.equalTo(kZEHeaderBaseInfoHight);
        }];
        

        
        
        
        UIView *midView = ({
            UIView *topView = [superView newUIView];
            
            UIView *segView = ({
                UIView *view = [topView newUIViewWithBgColor:[UIColor whiteColor]];
                self.segView = view;
                UIFont *font = [UIFont systemFontOfSize:14];
                UIButton *btn1 = [view newUIButton];
                btn1.titleLabel.font = font;
                [btn1 setTitle:@"商品" forState:UIControlStateNormal];
                [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [btn1 addTarget:self action:@selector(titleButtonClick0:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:btn1];
                self.segBtn0 = btn1;
                self.currentTitleButton = btn1;
                
                UIButton *btn2 = [view newUIButton];
                btn2.titleLabel.font = font;
                [btn2 setTitle:@"评价" forState:UIControlStateNormal];
                [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [btn2 addTarget:self action:@selector(titleButtonClick1:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:btn2];
                self.segBtn1 = btn2;
                
                UIView *lineView1 = [view newDefaultLineView];
                UIView *lineView2 = [view newDefaultLineView];
                self.segLineView = [view newUIViewWithBgColor:NAV_COLOR];
                
                [lineView1 makeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.top.equalTo(view);
                    make.height.equalTo(OnePixNumber);
                }];
                [lineView2 makeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.bottom.equalTo(view);
                    make.height.equalTo(OnePixNumber);
                }];
                [self.segLineView makeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(40);
                    make.height.equalTo(5);
                    make.bottom.equalTo(view.bottom).offset(-5);
                    make.centerX.equalTo(btn1.centerX);
                }];
                [btn1 makeConstraints:^(MASConstraintMaker *make) {
                    make.left.top.bottom.equalTo(view);
                    make.width.equalTo(60);
                }];
                [btn2 makeConstraints:^(MASConstraintMaker *make) {
                    make.top.bottom.width.equalTo(btn1);
                    make.left.equalTo(btn1.right);
                }];
                
                view;
            });
            [segView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(topView.top);
                make.left.right.equalTo(topView);
                make.height.equalTo(kSegBtnWidth);
            }];
            
            if (self.scrollView == nil) {
                self.scrollView = [topView newUIScrollView];
                self.scrollView.showsHorizontalScrollIndicator = NO;
                self.scrollView.showsVerticalScrollIndicator = NO;
                self.scrollView.scrollEnabled = YES;
                self.scrollView.pagingEnabled = YES;
                self.scrollView.bounces = NO;
                self.scrollView.backgroundColor = [UIColor whiteColor];
                self.scrollView.translatesAutoresizingMaskIntoConstraints  = NO;
                self.scrollView.contentSize = CGSizeMake(DEVICE_Width*2, DEVICE_Height/2);
                self.scrollView.delegate = self;
                [self.scrollView makeConstraints:^(MASConstraintMaker *make) {
                    make.left.right.bottom.equalTo(topView);
                    make.top.equalTo(segView.bottom);
                }];
                
                
                UIView *contentView = [self.scrollView newUIViewWithBgColor:[UIColor whiteColor]];
                contentView.tag = 101;
                contentView.translatesAutoresizingMaskIntoConstraints = NO;
                self.contentView = contentView;
                [contentView makeConstraints:^(MASConstraintMaker *make) {
                    make.left.top.equalTo(_scrollView);
                    make.height.equalTo(_scrollView.height);
                    make.width.equalTo(DEVICE_Width*2);
                }];
                
                
                self.classTableView = [[UITableView alloc] init];
                //self.classTableView.frame = CGRectMake(0, 0, kZEClassTableViewWidth, view.bounds.size.height);
                //self.classTableView.delegate = self;
                //self.classTableView.dataSource = self;
                self.classTableView.tableFooterView = UIView.new;
                self.classTableView.backgroundColor = [UIColor colorWithRed:0.961 green:0.965 blue:0.969 alpha:1.000];
                self.classTableView.showsVerticalScrollIndicator = NO;
                self.classTableView.tableFooterView = [UIView new];
                [contentView addSubview:_classTableView];
                
                self.tableView = [[QUTableView alloc] initWithFrame:CGRectZero];
                self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
                self.tableView.backgroundColor = [UIColor colorWithRed:0.996 green:1.000 blue:1.000 alpha:1.000];
                self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                self.tableView.tableFooterView = [UIView new];
                [contentView addSubview:self.tableView];
                
                self.commentTableView = [[QUTableView alloc] initWithFrame:CGRectZero];
                self.commentTableView.separatorStyle = UITableViewCellSelectionStyleNone;
                self.commentTableView.backgroundColor = [UIColor colorWithRed:0.996 green:1.000 blue:1.000 alpha:1.000];
                self.commentTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                self.commentTableView.tableFooterView = [UIView new];
                [contentView addSubview:self.commentTableView];
                
                
                [self.classTableView makeConstraints:^(MASConstraintMaker *make) {
                    make.top.bottom.left.equalTo(contentView);
                    make.width.equalTo(kZEClassTableViewWidth);
                }];
                [self.tableView makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_classTableView.right);
                    make.top.bottom.equalTo(contentView);
                    make.width.equalTo(DEVICE_Width-kZEClassTableViewWidth);
                }];
                [self.commentTableView makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(contentView.left).offset(DEVICE_Width);
                    make.top.bottom.equalTo(contentView);
                    make.width.equalTo(DEVICE_Width);
                }];
            }

            
            topView;
        });
        
        
        
        self.middleView = midView;
        
        
        [midView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(superView.top).offset(kZEHeaderBaseInfoHight);
            make.left.right.equalTo(superView);
            make.bottom.equalTo(superView.bottom).offset(-kZEFooterHight);
        }];
        
        self.cartView = [[FoodShopCarAndBottemView alloc] init];
        [superView addSubview:_cartView];
        [self.cartView makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(superView);
            make.height.equalTo(DEVICE_Height);
        }];
        
        [self.cartView hiddenShopList];
        
        
    }
    return self;
}

#pragma mark title点击事件处理
- (void)titleButtonClick0:(UIButton *)button {
    [self gotoTitleButtonIndex:0];
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)titleButtonClick1:(UIButton *)button
{
    [self gotoTitleButtonIndex:1];
    [self.scrollView setContentOffset:CGPointMake(DEVICE_Width, 0) animated:YES];
}


- (void)gotoTitleButtonIndex:(NSUInteger)index {
    
    if (index == 0) {
        self.segBtn1.transform = CGAffineTransformIdentity;
        [self.segBtn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.segBtn0 setTitleColor:NAV_COLOR forState:UIControlStateNormal];
        //self.segBtn0.transform = CGAffineTransformMakeScale(1.3, 1.3);
        

        [UIView animateWithDuration:0.2 animations:^{
            [self.segLineView remakeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(40);
                make.height.equalTo(5);
                make.bottom.equalTo(_segView.bottom).offset(-5);
                make.centerX.equalTo(_segBtn0.centerX);
            }];
        }];
    } else {
        self.segBtn0.transform = CGAffineTransformIdentity;
        [self.segBtn0 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.segBtn1 setTitleColor:NAV_COLOR forState:UIControlStateNormal];
        //self.segBtn1.transform = CGAffineTransformMakeScale(1.3, 1.3);
        
        [UIView animateWithDuration:0.2 animations:^{
            [self.segLineView remakeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(40);
                make.height.equalTo(5);
                make.bottom.equalTo(_segView.bottom).offset(-5);
                make.centerX.equalTo(_segBtn1.centerX);
            }];
        }];

    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat tableviewScrollX  = scrollView.contentOffset.x;
    NSUInteger index = tableviewScrollX / DEVICE_Width;
    [self gotoTitleButtonIndex:index];
}



@end



#pragma mark----FoodDetailNewTVC

@interface FoodDetailNewTVC ()<UITableViewDelegate, UITableViewDataSource, ImagePlayerViewDelegate, BMKLocationServiceDelegate>
{
    BMKLocationService *location;
}
@property(nonatomic,assign) NSInteger               classIndex; //选择哪一种类别

@property(nonatomic,strong) NSMutableArray*         tableArr;
@property(nonatomic,assign) BOOL                    isScrollDown; //是否为向下滚动

@property(nonatomic,assign) float                   kZEHeaderHight;//顶部高度

@property(nonatomic,strong) FoodContentView*        mainView; //主界面

@property(nonatomic,strong) NSMutableArray *        commentArr; //评论数据

@property(nonatomic,strong) NSMutableArray *        goodsArr; //商品分页所需数据
@property(nonatomic,assign) BOOL                    needPageShowGoods;//是否需要商品分页显示。在获取店铺信息列表时，没有返回商品列表，就需要分页取商品数据。


@property (nonatomic,strong)NSDictionary *dic;//评论数据


@end

@implementation FoodDetailNewTVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tableArr = [NSMutableArray array];
        self.commentArr = [NSMutableArray array];
        self.goodsArr = [NSMutableArray array];
        
        self.classIndex = -1;
        self.isScrollDown = YES;
        self.baseItem = [[Shop alloc] init];
    }
    return self;
}



-(void)loadView
{
    [super loadView];
    
    UIView *superView = self.view;
    
    [self loadNav];
    self.mainView = [[FoodContentView alloc] init];
    [superView addSubview:_mainView];
    [self.mainView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(superView);
        make.top.equalTo(superView.top).offset(NAVBAR_Height);
    }];


    self.mainView.headerView.shopImgLunView.imagePlayerViewDelegate = self;
    self.mainView.classTableView.delegate = self;
    self.mainView.classTableView.dataSource = self;
    self.mainView.tableView.delegate = self;
    self.mainView.tableView.dataSource = self;
    self.mainView.commentTableView.delegate = self;
    self.mainView.commentTableView.dataSource = self;
    
    [self.mainView.commentTableView setHaveHeaderFooter];

}



-(void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"店铺详情";
    
    //加载评论数据
    [self loadPJData];
    
    //先根据数据显示UI
    [self loadShopInfoUI];
    
    [self loadMap];
    
    //加载店铺基本数据
    [self loadShopData];
    
    //延迟加载评论列表数据
    [self.mainView.commentTableView performSelector:@selector(beginHeaderRereshing) withObject:nil afterDelay:0.3];

    
    
    //去结算
    [self.mainView.cartView.bottomView.buyBtn jk_addActionHandler:^(NSInteger tag) {
        NSArray *arr = [_mainView.cartView getGoodsInfoArrWithShopId:_baseItem.iD];
        
        GXDPPayViewController *pay = [[GXDPPayViewController alloc] init];
        pay.array = [NSMutableArray arrayWithArray:arr];
        pay.mid = _merid;
        pay.orderName = _name;
        NSString *price = [user objectForKey:@"SumPrice"];
        pay.locationCoorder = _locationCoorder;
        pay.price = price;
        [self.navigationController pushViewController:pay animated:YES];
        
    }];
    
    
    //评论列表刷新
    __weak typeof(self) weakSelf = self;
    self.mainView.commentTableView.refreshingBlock = ^(int page) {
        [[APIClient sharedClient] comentListWithShopId:weakSelf.baseItem.iD call:^(NSMutableArray *tableArr, APIObject *info) {
            [weakSelf.mainView.commentTableView doneLoadingTableViewDataWithTableArr:weakSelf.commentArr addArr:tableArr info:info];
        }];
    };

    
    //删除购物车时，刷新商品列表
    self.mainView.cartView.successClearnCallBack = ^{
        [weakSelf.mainView.tableView reloadData];
    };
    //修改购物车数量时，刷新商品列表
    self.mainView.cartView.successEditNumCallBack = ^(FoodGoods *item) {
        [weakSelf.mainView.tableView reloadData];
    };
}


- (void)loadMap{
    location = [[BMKLocationService alloc] init];
    [location startUserLocationService];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    location.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    location.delegate = nil;
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [location stopUserLocationService];
    
    //获取距离
    CLLocationCoordinate2D end = userLocation.location.coordinate;
    CLLocationCoordinate2D start = CLLocationCoordinate2DMake(_baseItem.latitude, _baseItem.longitude);
    [[APIClient sharedClient] getKmWithStart:start end:end call:^(float km, APIObject *info) {
        float fee = [self getFeeWithKm:km];
        [self.mainView.cartView setShippingFeeWithMoney:fee];
    }];
    
}

//通过公里数计算配送费
-(float)getFeeWithKm:(float)km
{
    float money = 0;
    NSArray *arr = [Shippingfee searchWithWhere:nil];
    if (arr.count > 0) {
        Shippingfee *fee = [arr objectAtIndex:0];

        float kmNow = fee.startkm;
        if (kmNow < km)
            kmNow = km;
        if (kmNow > fee.mixkm)
            kmNow = fee.mixkm;

        //超过公里数
        int kmChao = ceil(kmNow - fee.startkm); //向上取整
        
        money = fee.cost;
        NSLog(@"money = %f",money);
        money += kmChao * (fee.minxcost/fee.km);
    }
    return money;
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, NAVBAR_Height)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"店铺详情";
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //btn.backgroundColor = [UIColor redColor];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.left.equalTo(0);
        make.width.equalTo(40);
        make.height.equalTo(40);
    }];
}

// 返回
- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark----view处理

//判断并且滚动显示到对应商品id
-(NSIndexPath *)scrollToTagGoodsPath
{
    NSIndexPath *indexPath = nil;
    if (_needLinkToGoodsId.length > 0) {
        
        for (int i=0; i<self.tableArr.count; i++) {
            FoodCate* itemSection = [self.tableArr objectAtIndex:i];
            
            for (int j=0; j<itemSection.details.count; j++) {
                FoodGoods* item = [itemSection.details objectAtIndex:j];
                if ([item.iD isEqualToString:_needLinkToGoodsId]) {
                    indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                    break;
                }
            }
        }
    }
    return indexPath;
}





-(void)loadShopInfoUI
{
    BOOL canEnabled = YES;
    self.mainView.cartView.bottomView.userInteractionEnabled = canEnabled;
    

    [self.mainView.headerView.shopImgLunView reloadData];
    self.mainView.headerView.shopNameLable.text = _baseItem.name.length>0 ? _baseItem.name : @"暂无店铺名称";
    self.mainView.headerView.shopDesLable.text = _baseItem.profile.length>0 ? _baseItem.profile : @"暂无店铺描述";
    self.mainView.headerView.shopAddressLable.text = _baseItem.suite.length>0 ? _baseItem.suite : @"暂无地址";
    //self.mainView.headerView.shopOrderLable.text = @"订单总数：215";
    self.mainView.headerView.starView.value = _baseItem.star;
    
    NSDictionary* style = @{@"body1" : @[[UIFont systemFontOfSize:11], [UIColor blackColor]],
                            @"body2" : @[[UIFont boldSystemFontOfSize:12], [UIColor redColor]] };
    NSString *orderStr = [NSString stringWithFormat:@"<body1>订单总数：</body1><body2>%i</body2>", _baseItem.order];
    self.mainView.headerView.shopOrderLable.attributedText = [orderStr attributedStringWithStyleBook:style];

    if (self.tableArr.count > 0) {
        self.mainView.classTableView.hidden = NO;
        self.mainView.tableView.hidden = NO;
    } else {
        self.mainView.classTableView.hidden = YES;
        self.mainView.tableView.hidden = YES;
    }

    self.kZEHeaderHight = kZEHeaderBaseInfoHight;
    
    [self scrollViewDidScroll:self.mainView.tableView];
}




#pragma mark - ImagePlayerViewDelegate
- (NSInteger)numberOfItems
{
    return _baseItem.figurepic.count>0 ? _baseItem.figurepic.count : 1;
}

- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView loadImageForImageView:(UIImageView *)imageView index:(NSInteger)index
{
    imageView.image = IMG(@"timg.png");
    if (_baseItem.figurepic.count > index) {
        NSString *item = [_baseItem.figurepic objectAtIndex:index];
        NSURL *str = [NSURL URLWithString:item];
        [imageView setImageWithURL:str placeholderImage:IMG(@"TIM截图20170819150938")];
    } else
        imageView.image = IMG(@"TIM截图20170819150938");
}


#pragma mark----view滚动处理
-(void)setHeaderViewOriginY:(CGFloat)y
{
    UIView *superView = self.mainView;
    [self.mainView.middleView updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView.top).offset(y);
    }];
    
//    CGRect rect = _middleView.frame;
//    rect.origin.y = y;
//    rect.size.height = DEVICE_Height-y-kZEFooterHight;
//    _middleView.frame = rect;
//    
//    MLLog(@"_middleView.frame: %@", NSStringFromCGRect(_middleView.frame));
//    CGRect rect = _headerView.frame;
//    rect.origin.y = y;
//    _headerView.frame = rect;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _mainView.tableView || scrollView==_mainView.commentTableView) {
        static CGFloat lastOffsetY = 0;
        
        CGFloat tableviewScrollY  = scrollView.contentOffset.y;
        
        CGFloat need_height = _kZEHeaderHight - NAVBAR_Height;
        
        if (tableviewScrollY >= need_height) {
            [self setHeaderViewOriginY:NAVBAR_Height];
            
        } else if (tableviewScrollY <= 0 ) {
            
            [self setHeaderViewOriginY:_kZEHeaderHight];

            
            
        } else{
            CGFloat aa = _kZEHeaderHight - tableviewScrollY;
            [self setHeaderViewOriginY:aa];
        
        }
        
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
        
    }
    
}



#pragma mark----商品列表需要分页时操作

-(void)selectPageClassIndex:(NSInteger)row
{
//    if (_tableArr.count > 0) {
//        if (_tableArr.count > row) {
//            if (row != _classIndex) {
//                self.classIndex = row;
//                [self.mainView.classTableView reloadData];
//                [self restartPageGoodsTableView];
//            }
//        }
//    }
//    else
//        [SVProgressHUD showErrorWithStatus:@"没有分类"];
}
//
//-(void)restartPageGoodsTableView
//{
//    [self.goodsArr removeAllObjects];
//    [self.mainView.tableView reloadData];
//    [self.mainView.tableView beginHeaderRereshing];
//
//    __weak typeof(self) weakSelf = self;
//    self.mainView.tableView.refreshingBlock = ^(int page) {
//        FoodCate *sectionItem = [weakSelf.tableArr objectAtIndex:weakSelf.classIndex];
//
//        [[APIClient sharedClient] foodGoodsListWithTag:weakSelf shop_id:weakSelf.baseItem.shop_id gcate_id:sectionItem.gcate_id search_title:nil page:page call:^(NSArray *tableArr, APIObject *info) {
//
//            [weakSelf.mainView.tableView doneLoadingTableViewDataWithTableArr:weakSelf.goodsArr addArr:tableArr info:info];
//        }];
//
//    };
//}

#pragma mark----加载数据

//加载基础数据
-(void)loadShopData
{
    [SVProgressHUD showWithStatus:@"加载中..."];
    [[APIClient sharedClient] goodsListWithShopId:_baseItem.iD call:^(NSMutableArray *tableArr, APIObject *info) {
        if (tableArr.count > 0) {
            NSLog(@"tableArr:%@",tableArr);
            
            [self.tableArr setArray:tableArr];
            [self.mainView.classTableView reloadData];
            [self.mainView.tableView reloadData];
            
            [self loadShopInfoUI];
            
            self.mainView.cartView.starting_price = 1;
            [self.mainView.cartView updateBottomViewUIWithData];
            
            self.needPageShowGoods = NO;
            
            if (_needPageShowGoods == NO) {
                //如果需要滚动到对应商品，则调用
                NSIndexPath *indexPath = [self scrollToTagGoodsPath];
                if (indexPath != nil)
                    [self scrollToTableViewIndexPath:indexPath];
                else
                    [self selectClassIndex:0];
            } else {
                [self.mainView.tableView setHaveHeaderFooter];
                [self selectPageClassIndex:0];
            }
            
            [SVProgressHUD dismiss];
        } else
            [SVProgressHUD showErrorWithStatus:info.msg];
    }];
    
    
//    //加载店铺评论标签数据
//    [[APIClient sharedClient] shopCommentSummaryListWithTag:self shop_id:_baseItem.shop_id call:^(float pingfen, NSArray *tableArr, APIObject *info) {
//        if (pingfen > 0)
//            [self.mainView.segBtn1 setTitle:[NSString stringWithFormat:@"评价(%.1f分)", pingfen] forState:UIControlStateNormal];
//
//        if (tableArr.count > 0)
//            [self.commentSummaryArr setArray:tableArr];
//
//        [self.mainView.commentTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
//    }];
}


#pragma mark----评论图片查看
//
//- (void)photosView:(PYPhotosView *)photosView willHiddenWithPhotos:(NSArray<PYPhoto *> *)photos index:(NSInteger)index
//{
//    [self.mainView.commentTableView reloadData];
//}

#pragma mark----tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.mainView.tableView) {
        if (_needPageShowGoods) {
            return 1;
        } else {
            if (_tableArr.count > 0)
                return _tableArr.count;
        }
    }
    else if (tableView == _mainView.commentTableView) {
        return 1; //评论列表
    }
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _mainView.classTableView) {
        if (_tableArr.count > 0)
            return _tableArr.count;
    }
    else if (tableView == _mainView.tableView) {
        if (_needPageShowGoods) {
            return _goodsArr.count;
        } else {
            if (_tableArr.count > 0) {
                FoodCate *it = [_tableArr objectAtIndex:section];
                return it.details.count;
            }
        }
    }
    else if (tableView == _mainView.commentTableView) {
        NSArray *arr = [_dic objectForKey:@"comment"];
        return arr.count;
//        return _commentArr.count>0 ? _commentArr.count : 1;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _mainView.tableView ) {
        if (_tableArr.count > 0)
            return 80;
    }
    else if (tableView==_mainView.classTableView ) {
        if (_tableArr.count > 0)
            return 40;
    }
//    else if (tableView == _mainView.cartView.mShopCarView.mShopCarListView ) {
//        return kShopCarListView_CellViewHeight;
//        
//    }
    else if (tableView == _mainView.commentTableView ) {
        
        return 100.0;
        /*
        if (_commentArr.count > 0) {
            OrderCommentObject* item = [self.commentArr objectAtIndex:indexPath.row];
            NSString *str = item.comment.length>0 ? item.comment : @"未填写评论内容";
            CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:15]
                          constrainedToSize:CGSizeMake([ShopCommentTableViewCell commentLableWidth], MAXFLOAT)
                              lineBreakMode:NSLineBreakByWordWrapping];
            if (size.height < 20)
                size.height = 20;
            CGFloat height = size.height + kShopCommentTableViewCell_BaseHeight;
            
            return height;
        }*/
    }
    return 50;
}
//头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _mainView.tableView) {
        if (_needPageShowGoods) {
            return 0;
        } else {
            if (_tableArr.count > 0)
                return 30;
        }

    } else if (tableView == _mainView.cartView.mShopCarView.mShopCarListView && section==0) {
        return 0;
    }else if (tableView == _mainView.commentTableView){
        return 40.0;
    }
    return 0;
}
//尾视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView == _mainView.commentTableView) {
        return 0.0;
    }
    return 0;
}
//尾视图
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40.0)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, ScreenWidth, 40.0);
    [btn setTitle:@"查看全部评价" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/2+35, 14, 60, 12)];
    NSArray *plArray = [_dic objectForKey:@"comment"];
    NSInteger count = plArray.count;
    lab.text = [NSString stringWithFormat:@"(%li)",count];
    
    lab.font = [UIFont systemFontOfSize:12.0];
    lab.textColor = [UIColor redColor];
    [view addSubview:lab];
    
    return view;
    
}
//查看评论
- (void)click{
    PingJiaViewController *pinjia = [[PingJiaViewController alloc] init];
    pinjia.merid = _merid;
    NSString *state = [user objectForKey:@"gxsg"];
    if ([state isEqualToString:@"gx"]) {
        pinjia.url = [NSString stringWithFormat:@"%@/App/Merchantcomment/cleaning",urlHead];
    }else{
        pinjia.url = [NSString stringWithFormat:@"%@/App/Merchantcomment/vegetables",urlHead];
    }
    [self.navigationController pushViewController:pinjia animated:YES];
}


// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向上，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((self.mainView.tableView == tableView) && !_isScrollDown && self.mainView.tableView.dragging && _needPageShowGoods==NO)
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向下，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((self.mainView.tableView == tableView) && _isScrollDown && self.mainView.tableView.dragging && _needPageShowGoods==NO)
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

//头视图
-(nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _mainView.tableView) {
        if (_needPageShowGoods) {
            return nil;
        } else {
            if (_tableArr.count > 0) {
                FoodCate *it = [_tableArr objectAtIndex:section];
                
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.mainView.tableView.bounds.size.width, 30)];
                view.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
                UILabel *lable = [view newUILableWithText:it.clasname];
                lable.frame = cgr(10, 0, view.bounds.size.width-20, view.bounds.size.height);
                lable.font = [UIFont systemFontOfSize:15];
                lable.adjustsFontSizeToFitWidth = YES;
                lable.minimumScaleFactor = 0.8;
                return view;
            }
        }
    }else if (tableView == _mainView.commentTableView){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *lab = [[UILabel alloc] init];
        lab.text = @"店铺评价";
        lab.font = [UIFont systemFontOfSize:15.0];
        [view addSubview:lab];
        [lab makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view.left).offset(16);
            make.centerY.equalTo(view.centerY);
        }];
        
        UILabel *lab2 = [[UILabel alloc] initWithFrame:CGRectMake(16, 39, ScreenWidth-32, 0.5)];
        lab2.backgroundColor = [UIColor grayColor];
        [view addSubview:lab2];
        
        NSString *evaluate = [[_dic objectForKey:@"commentcount"] objectForKey:@"evaluate"];
        CGFloat count = [evaluate floatValue];
        StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(ScreenWidth-100, 10, 100, 20)];
        starView.showStar = count * 20;
        [view addSubview:starView];
        
        return view;
    }
    return nil;
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _mainView.classTableView) { //商品分类列表
        static NSString *CellIdentifier = @"ClassGoodsTableViewCell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.backgroundColor = [UIColor clearColor];
            UIView *superView = cell.contentView;
            UILabel *lable = [cell.contentView newUILableWithText:@"" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:14] textAlignment:QU_TextAlignmentCenter];
            lable.numberOfLines = 2;
            lable.tag = 11;
            int padding = 5;
            [lable makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(superView.left).offset(padding);
                make.right.equalTo(superView.right).offset(-padding);
                make.top.bottom.equalTo(superView);
                //make.edges.equalTo(superView);
            }];
        }
        UILabel *lable = (UILabel *)[cell.contentView viewWithTag:11];
        if (_classIndex == indexPath.row) {
            lable.textColor = NAV_COLOR;
            cell.contentView.backgroundColor = [UIColor whiteColor];
        } else {
            lable.textColor = [UIColor colorWithWhite:0.3 alpha:1];
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.961 green:0.965 blue:0.969 alpha:1.000];
        }
        
        FoodCate* item = [self.tableArr objectAtIndex:indexPath.row];
        lable.text = item.clasname;
        
        return cell;
        
        
    }
    else if (tableView == _mainView.tableView) { //商品列表
        static NSString *CellIdentifier = @"ClassGoodsTableViewCell2";
        FoodGoodsTableViewCell *cell = (FoodGoodsTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell= [[FoodGoodsTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier isCartCell:NO];
            //cell.backgroundColor = [UIColor clearColor];
        }
        FoodGoods* item = nil;
        if (_needPageShowGoods) {
            item = [self.goodsArr objectAtIndex:indexPath.row];
        } else {;
            FoodCate* itemSection = [self.tableArr objectAtIndex:indexPath.section];
            item = [itemSection.details objectAtIndex:indexPath.row];
        }
        
        [cell loadUIWithItem:item];
        
        cell.count = [_mainView.cartView countFromCartDicWithId:item.iD];
        
        cell.addBtn.hidden = NO;
        //减操作
        cell.jianCallBack = ^(int count, FoodGoodsTableViewCell *tagCell) {
            item.num = count;
            [self.mainView.cartView setCartArrWithItem:item];
        };
        //加操作
        cell.addCallBack = ^(int count, FoodGoodsTableViewCell *tagCell) {
            item.num = count;
            [self.mainView.cartView setCartArrWithItem:item];

            CGRect imageViewRect = [tagCell.addBtn convertRect:tagCell.addBtn.bounds toView:self.view];
            [[PurchaseCarAnimationTool shareTool] startAnimationandView:tagCell.addBtn andRect:imageViewRect andFinisnRect:CGPointMake(20, ScreenHeight-50) andFinishBlock:^(BOOL finisn){
                
                [PurchaseCarAnimationTool shakeAnimation:_mainView.cartView.bottomView.cartLogoBtn];
            }];
        };
        
        return cell;
        
    }
    else if (tableView == _mainView.commentTableView) { //评价列表
        NSArray *arr = [_dic objectForKey:@"comment"];
        if (arr.count > 0) {
            static NSString *cellId = @"Cell0";
            PinJiaCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (!cell) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"PinJiaCell" owner:nil options:nil] lastObject];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            NSArray *plArray = [_dic objectForKey:@"comment"];
            NSDictionary *dic = plArray[indexPath.row];
            cell.labName.text = [dic objectForKey:@"nickname"];
            cell.labText.text = [dic objectForKey:@"comment"];
            
            NSString *time = [dic objectForKey:@"commenttime"];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time integerValue]];
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            [df setDateFormat:@"YYYY-MM-dd hh:mm"];
            NSString *timeStr = [df stringFromDate:date];
            cell.labDate.text = timeStr;
            
            
            NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[dic objectForKey:@"avatar"]];
            cell.images.layer.cornerRadius = 11.5;
            cell.images.layer.masksToBounds = YES;
            [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"TIM图片20170810135854"]];
            
            NSString *star = [dic objectForKey:@"star"];
            CGFloat count = [star floatValue];
            StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
            starView.showStar = count * 20;
            [cell.starView addSubview:starView];
            
            return cell;
        }else{
            
        }
        
//        NSLog(@"commentArr:%@",_commentArr);
        if (_commentArr.count > 0) {
            static NSString *CellIdentifier = @"ShopCommentTableViewCell";
            ShopCommentTableViewCell *cell = (ShopCommentTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell= [[ShopCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            }
            
            OrderCommentObject* item = [self.commentArr objectAtIndex:indexPath.row];
            //cell.nameLable.text = item.member_name.length>0 ? item.member_name : @"匿名用户";
            cell.nameLable.text = @"匿名用户";
            cell.commentLable.text = item.comment.length>0 ? item.comment : @"未填写评论内容";
            cell.timeLable.text = [[NSDate dateWithTimeIntervalSince1970:item.commenttime] formattedDateWithFormat:@"yyyy-MM-dd"];
            [cell.logoImgView setImageWithURL:[NSURL URLWithString:item.avatar] placeholderImage:IMG(@"timg.png")];
            cell.starView.value = item.star;
            
            
            return cell;
            
        } else {
            static NSString *CellIdentifier = @"ShopCommentTableViewCell111";
            UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
                cell.textLabel.font = [UIFont systemFontOfSize:12];
                UILabel *lable1 = [cell.contentView newUILableWithText:@"暂无评论" textColor:[UIColor blackColor] font:[UIFont systemFontOfSize:15] textAlignment:NSTextAlignmentCenter];
                [lable1 makeConstraints:^(MASConstraintMaker *make) {
                    make.edges.equalTo(cell.contentView);
                }];
            }
            
            return cell;
        }
        
        
    }

    return nil;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_mainView.classTableView == tableView) {
        if (_needPageShowGoods)
            [self selectPageClassIndex:indexPath.row];
        else
            [self selectClassIndex:indexPath.row];
        
    }
    else if (_mainView.tableView == tableView) {
        FoodGoods* item = nil;
        if (_needPageShowGoods) {
            item = [self.goodsArr objectAtIndex:indexPath.row];
        } else {
            FoodCate* itemSection = [self.tableArr objectAtIndex:indexPath.section];
            item = [itemSection.details objectAtIndex:indexPath.row];
        }
        
//        int count = [self.mainView.cartView countFromCartDicWithId:item.iD];
//
//        FoodGoodsInfoView *view = [[FoodGoodsInfoView alloc] init];
//        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        [delegate.window addSubview:view];
//        [view makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo(delegate.window);
//        }];
//
//        //加载数据
//        [view loadUIWithItem:item count:count];
//
//        __weak __typeof(FoodGoodsInfoView *)weakSelf = view;
//        view.resultBlock = ^(int number, BOOL isCloseView) {
//            item.num = number;
//            [self.mainView.cartView setCartArrWithItem:item];
//            [self.mainView.tableView reloadData];
//
//            if (isCloseView) {
//                CGRect imageViewRect = [weakSelf.addCartBtn convertRect:weakSelf.addCartBtn.bounds toView:self.view];
//                [[PurchaseCarAnimationTool shareTool] startAnimationandView:weakSelf.addCartBtn andRect:imageViewRect andFinisnRect:CGPointMake(20, ScreenHeight-50) andFinishBlock:^(BOOL finisn){
//                    [PurchaseCarAnimationTool shakeAnimation:_mainView.cartView.bottomView.cartLogoBtn];
//                }];
//            }
//
//        };
    }
}


#pragma mark----选择点击行

-(void)selectClassIndex:(NSInteger)index
{
    self.classIndex = index;
    [self.mainView.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [self.mainView.classTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [self.mainView.classTableView reloadData];
}

-(void)scrollToTableViewIndexPath:(NSIndexPath *)indexPath
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.classIndex = indexPath.section;
        [self.mainView.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [self.mainView.classTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [self.mainView.classTableView reloadData];
    });
}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.classIndex = index;
        [self.mainView.classTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        [self.mainView.classTableView reloadData];
    });
}


//评论数据
- (void)loadPJData{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_merid forKey:@"merchantid"];
    NSString *url;
    NSString *state = [user objectForKey:@"gxsg"];
    if ([state isEqualToString:@"gx"]) {
        url = [NSString stringWithFormat:@"%@/App/Merchantcomment/cleaning",urlHead];
    }else{
        //vegetables
        url = [NSString stringWithFormat:@"%@/App/Merchantcomment/vegetables",urlHead];
    }
    [[AFHTTPSessionManager manager] GET:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"评论res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            _dic = [responseObject objectForKey:@"result"];
        }
        
        [_mainView.commentTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}


@end
